#/bin/bash
CG_ROOT_DIR="/cgroup"
CG_CPUSET_DIR="$CG_ROOT_DIR/cpuset"
CG_CPU_DIR="$CG_ROOT_DIR/cpu"
CG_MEM_DIR="$CG_ROOT_DIR/memory"
CONF="/usr/local/cgroup/cgconfig"

if [ $# -lt 2 ];then

	     /bin/echo "useage:  cgctrl.sh  create  kvmname"
	     /bin/echo "         cgctrl.sh  delete  kvmname" 
	     exit 
fi

#if [ ! -f "$CONF" ];then
#        /bin/echo not found config file $CONF,exit..
#        exit 3
#fi
#check cgroup status
if ! service cgconfig status |grep -i running > /dev/null;then
        /bin/echo "cgconfig service not start"
        exit 1;
fi
qemu_dir=$2
if [ "$1" == "delete" ];then
#	for set in  cpu
#	do
#		echo $set delete $qemu_dir
#		if [ $set == cpu ];then
#			cgdelete -r $set:$qemu_dir
#			continue	
#		fi
#		cgdelete -r $set:qemu/$qemu_dir
#
#		if [ $? != 0 ];then
#			/bin/echo remove $set failed for $2
#		fi
#	done
## do nothing 

	exit;
fi

pid=$(ps aux |grep "$qemu_dir" |grep -v grep |grep  -v $0|awk '{print $2}')

if [ -z "$pid" ];then
	pid=$(echo $qemu_dir |sed -n 's/-.*//p')
	if [ -z "$pid" ];then
		/bin/echo "kvm not start\n"
		exit 1
	fi
fi	

config=$3;

if [ -z "$config" ];then
	/bin/echo please set config
	exit 2
fi

if [ ! -f "$config" ];then
	/bin/echo not found $config
	exit 2
fi

. $config

if [ $? != 0 ];then
	/bin/echo load config $config failed 
	exit 2
fi

MEM_NODE=`cat /proc/zoneinfo  |grep Node |awk  -F ",| " 'BEGIN{ORS=","}{a[$2]++}END{for(i in a){print i}}'|sed 's/,$//'`
for dir in cpu memory cpuset
do

	if [ "$dir" == "cpu" ];then
		if [ ! -d "$CG_ROOT_DIR/cpu/qemu" ];then  	
			mkdir  $CG_ROOT_DIR/$dir/qemu
		fi	
#		/bin/echo period $PERIOD_US
			/bin/echo $PERIOD_US > $CG_ROOT_DIR/cpu/qemu/cpu.rt_period_us
#		/bin/echo runtime $RUNTIME_US
			/bin/echo $RUNTIME_US > $CG_ROOT_DIR/cpu/qemu/cpu.rt_runtime_us
	elif [ "$dir" == "cpuset" ];then
		if [ ! -d "$CG_ROOT_DIR/cpuset/qemu/" ];then
			mkdir $CG_ROOT_DIR/$dir/qemu/
		fi
		
#		echo $MEM_NODE > $CG_ROOT_DIR/cpuset/qemu/cpuset.mems
#		echo $CPUSET  > $CG_ROOT_DIR/cpuset/qemu/cpuset.cpus
#		mkdir -p $CG_ROOT_DIR/$dir/qemu/$qemu_dir
			echo memnode $MEM_NODE
#		echo $CG_ROOT_DIR/cpuset/qemu/$qemu_dir/cpuset.mems
			/bin/echo $MEM_NODE > $CG_ROOT_DIR/cpuset/qemu/cpuset.mems
			/bin/echo cpuset $CPUSET
			/bin/echo $CPUSET   > $CG_ROOT_DIR/cpuset/qemu/cpuset.cpus
		
	elif [ "$dir" == "memory" ];then
		if [ ! -d "$CG_ROOT_DIR/$dir/qemu/" ];then
			mkdir  $CG_ROOT_DIR/$dir/qemu/
		fi
		if test -f $CG_ROOT_DIR/memory/qemu/memory.oom_control;then	
			/bin/echo 1 >  $CG_ROOT_DIR/memory/qemu/memory.oom_control 
		fi	
			/bin/echo swap $SWAP
			/bin/echo $SWAP > $CG_ROOT_DIR/memory/qemu/memory.swappiness
			/bin/echo MEMLIMIT $MEMLIMIT
			/bin/echo $MEMLIMIT > $CG_ROOT_DIR/memory/qemu/memory.limit_in_bytes
	fi

	for tid in $(ls /proc/$pid/task)
        do
	#	echo tid $tid
                /bin/echo  $tid >  $CG_ROOT_DIR/$dir/qemu/tasks
        done

done
